package cmd

import (
	"context"
	"fmt"
	"log"
	"os"
	"os/exec"
	"strconv"
	"time"

	"advertising/config"
	"advertising/config/redis"
	grpc "advertising/internal/app/grpc/service"
	"advertising/internal/app/web/middleware"
	"advertising/internal/define"
	"advertising/internal/routers"

	"github.com/fvbock/endless"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
	Use:   "hugo",
	Short: "Hugo is a very fast static site generator",
	Long: `A Fast and Flexible Static Site Generator built with
                love by spf13 and friends in Go.
                Complete documentation is available at http://hugo.spf13.com`,
	// 当没有命令参数时，自动执行的函数
	// 否则不会执行下面的函数
	Run: func(*cobra.Command, []string) {
		// 缓存应用的版本
		ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
		defer cancel()
		rdb := redis.NewDB()
		rdb.Set(ctx, define.RedisAppVersion, define.APPVersion, 0).Result()
		// 监听重启信号,并进行重启
		grpcCtx, grpcCancel := context.WithCancel(context.Background())
		defer grpcCancel()
		// 监听重启信号,并进行重启
		{
			tk := time.NewTicker(time.Second)
			defer tk.Stop()
			// 重启检查
			if !config.Config.DisableRestartCheck {
				go func() {
					for range tk.C {
						redisCtx, redisCtxCancel := context.WithTimeout(context.Background(), time.Second*3)
						ver, err := redis.NewDB().Get(redisCtx, define.RedisAppVersion).Result()
						redisCtxCancel()
						if err == nil {
							if ver != define.APPVersion {
								grpcCancel()
								cmd := exec.Command("kill", "-1", strconv.Itoa(os.Getpid()))
								cmd.Run()
								return
							}
						}
					}
				}()
			}
		}
		// 启动grpc
		go func() {
			grpc.StartGrpc(grpcCtx, config.Config.GRPCPort)
		}()
		// 启动http服务
		{
			router := gin.Default()
			// 注册中间件
			router.Use(
				middleware.Cors(), // 跨域
			)

			if config.Config.LogTracing {
				router.Use(middleware.TraceMiddleware())
			}
			// 注册路由
			routers.Default(router)
			endless.DefaultHammerTime = time.Second * 5
			endless.ListenAndServe(":"+config.Config.HTTPPort, router)
		}
		log.Println("advertising restart")
		os.Exit(0)
	},
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
